<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 5/25/21
 * Time: 8:55 PM
 */

namespace app\api\controller\v1;

use app\api\model\StoreGroup as StoreGroupModel;
use app\api\model\StoreUser as StoreUserModel;
use app\lib\exception\TokenException;
use LinCmsTp5\exception\ParameterException;
use think\facade\Cache;

// 分组信息
class StoreGroup
{
    /**
     * 获取所有分组列表
     */
    public function getDataAll($store_id)
    {
        $where = [];
        if($store_id) {
            $where[] = ['store_id', 'eq', $store_id];
        }
        return StoreGroupModel::where($where)->order('id desc')->select()->toArray();
    }


    /**
     * 获取分组列表
     * @validate('PagingParameter')
     */
    public function getDataList($name,$store_id,$page,$limit)
    {
        $where = [];
        if($name) {
            $where[] = ['name','like','%'.$name.'%'];
        }
        if($store_id) {
            $where[] = ['store_id', 'eq', $store_id];
        }
        $query = StoreGroupModel::where($where)->with('store')->order('id desc');
        $count = $query->count();
        $result = $query->page($page, $limit)->select()->toArray();
        $data['count'] = $count;
        $data['data'] = $result;
        return $data;
    }

    /**
     * 获取店面详情
     * @validate('IdMustBePositiveInt')
     */
    public function getDataInfo($id)
    {
        return StoreGroupModel::get($id);
    }

    /**
     * 添加店面信息
     * @validate("CheckStoreGroup")
     */
    public function createData($name,$desc,$remarks,$store_id)
    {
        StoreGroupModel::create([
            'name' => $name,
            'store_id' => $store_id,
            'desc' => $desc,
            'remarks' => $remarks,
        ]);
        return writeJson(201, [], '添加成功！');
    }


    /**
     * 修改店面信息
     * @validate("CheckStoreGroup")
     */
    public function updateData($id,$name,$remarks,$store_id,$desc)
    {
        $info = StoreGroupModel::get($id);
        if($info) {
            $info->name = $name;
            $info->store_id = $store_id;
            $info->desc = $desc;
            $info->remarks = $remarks;
            $info->save();
        }
        return writeJson(202, [], '修改成功！');
    }

    /**
     * 删除店面信息
     * @validate('IdMustBePositiveInt')
     */
    public function deleteData($id)
    {
        // 关联员工
        $shopStaff = StoreUserModel::where('group_id',$id)->select();
        if(!$shopStaff->isEmpty()) {
            throw new ParameterException([
                'msg' => [
                    'store' => '分组下还有关联员工,不能删除分组！'
                ]
            ]);
        }
        StoreGroupModel::destroy($id);
        return writeJson(202, [], '删除成功！');
    }
}